package router

import (
	"apibe/chat/v1/hub"
	"apibe/single/src/v1/share/logger"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/streadway/amqp"
	"net/http"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

/*
	WsChat 聊天核心组件 权限是auth的玩家以userID的名义连入roomID房间内
*/
func WsChat(c *gin.Context) {
	roomid := c.Param("roomid") // 用roomid来区分当前人物所处的区域
	userid := c.Param("userid") // 用userid来区分不同的用户
	if roomid == "" || userid == "" {
		return
	}
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		logger.Logger.Error(err)
		return
	}
	conn := &hub.Connect{Ws: ws}
	m := hub.Message{Exchange: "word.roomid", Kind: amqp.ExchangeDirect, Queue: roomid, Routing: roomid, Userid: userid, Connect: conn}
	// 有玩家主动加入了连接
	fmt.Println("有玩家主动加入了连接")
	go m.Pub() // 消息队列生产控制
	go m.Sub() // 消息队列写入控制
}
